package team.seekers.oj.course.conventer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.assertj.core.util.Lists;
import team.seekers.oj.common.converter.BaseConvertUtils;
import team.seekers.oj.course.client.UserClient;
import team.seekers.oj.lesson.dto.ChapterListDTO;
import team.seekers.oj.user.api.UserApi;

import java.io.*;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description DTO-DO 特殊转换方法的统一收口处
 * @author hbc
**/
public class CourseConvertUtils extends BaseConvertUtils {


    public static List<Long> participantsTo(byte[] groups) {
        if (groups == null) {
            return Lists.newArrayList();
        }
        ByteBuffer wrap = ByteBuffer.wrap(groups);
        List<Long> groupUserIdList = new ArrayList<>(groups.length / 8);
        for (int i = 0, n = groups.length; i < n; i += 8) {
            groupUserIdList.add(wrap.getLong(i));
        }
        return groupUserIdList;
    }

    public static byte[] participantsFrom(List<Long> groups) {
        ByteBuf byteBuf = Unpooled.buffer(groups.size() * 8);
        groups.forEach(byteBuf::writeLong);
        return byteBuf.array();
    }

    public static List<ChapterListDTO> chaptersSectionsToChapterList(byte[] chaptersSections) throws IOException, ClassNotFoundException {
        //将取出的二进制数据反序列化成序列化的对象，依旧使用对象流处理
        if(chaptersSections == null){
            return new ArrayList<ChapterListDTO>();
        }
        ByteArrayInputStream byteInt=new ByteArrayInputStream(chaptersSections);
        ObjectInputStream objInt=new ObjectInputStream(byteInt);
        List<ChapterListDTO> o=(List<ChapterListDTO>)objInt.readObject();
        return o;
    }

    public static byte[] chaptersSectionsFromChapterList(List<ChapterListDTO> ChapterListDTOList) throws IOException {
        ByteArrayOutputStream byt=new ByteArrayOutputStream();
        ObjectOutputStream obj=new ObjectOutputStream(byt);
        obj.writeObject(ChapterListDTOList);
        return byt.toByteArray();
    }

    public static String stringDateFromDate(Date date){
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        return f.format(date);
    }
}